﻿#include "Stack"

void Stack::Init(int n)
{
	_arr = (STDataType*)malloc(n * sizeof(STDataType));
	if (_arr == nullptr)
	{
		printf("申请空间失败");
		perror("class Stack::STInit");
		return;
	}
	_capacity = n;
	_top = 0;
}
void Stack::Push(STDataType x)
{
	if (_top == _capacity)
	{
		//空间满了--增容
		int newCapacity = _capacity == 0 ? 4 : 2 * _capacity;
		STDataType* tmp = (STDataType*)realloc(_arr, newCapacity * sizeof(STDataType));
		if (tmp == NULL)
		{
			perror("realloc fail!\n");
			exit(1);
		}
		_arr = tmp;
		_capacity = newCapacity;
	}
	//空间足够
	_arr[_top++] = x;
}

bool Stack::Empty()
{
	
	return _top == 0;
}

void Stack::Pop()
{
	assert(!Empty());
	--_top;

}

STDataType Stack::Top()
{
	assert(!Empty());
	return _arr[_top - 1];
}


//获取栈中有效元素个数
int Stack::Size()
{
	return _top;
}

void Stack::Destroy()
{
	free(_arr);
	_arr = nullptr;
	_top = _capacity = 0;
}
